package com.marvels.financial.pay.hlbpay.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.pay.hlbpay.dto.Constant;
import com.marvels.financial.pay.hlbpay.dto.HlbBindCardDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbDirectPaymentDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbDirectPaymentQueryDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbPrebindCardDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbReturnDTO;
import com.marvels.financial.pay.hlbpay.dto.config.HlbConfig;
import com.marvels.financial.pay.hlbpay.dto.request.BindCardSendValidateCodeVo;
import com.marvels.financial.pay.hlbpay.dto.request.ConfirmBindCardVo;
import com.marvels.financial.pay.hlbpay.dto.request.ConfirmBindPayVo;
import com.marvels.financial.pay.hlbpay.dto.request.MerchantUserQueryVo;
import com.marvels.financial.pay.hlbpay.dto.request.MerchantUserUploadVo;
import com.marvels.financial.pay.hlbpay.dto.request.MerchantUserVo;
import com.marvels.financial.pay.hlbpay.dto.request.OrderQueryVo;
import com.marvels.financial.pay.hlbpay.dto.request.OrderVo;
import com.marvels.financial.pay.hlbpay.dto.request.QueryOrderVo;
import com.marvels.financial.pay.hlbpay.dto.request.QuickPayBindCardPreOrderVo;
import com.marvels.financial.pay.hlbpay.dto.request.QuickPayBindPayPreOrderVo;
import com.marvels.financial.pay.hlbpay.dto.response.BindCardPreOrderResponseVo;
import com.marvels.financial.pay.hlbpay.dto.response.BindCardSendValidateCodeResponseVo;
import com.marvels.financial.pay.hlbpay.dto.response.ConfirmBindCardResponseVo;
import com.marvels.financial.pay.hlbpay.dto.response.ConfirmBindPayResponseVo;
import com.marvels.financial.pay.hlbpay.dto.response.MerchantUserQueryResVo;
import com.marvels.financial.pay.hlbpay.dto.response.MerchantUserResVo;
import com.marvels.financial.pay.hlbpay.dto.response.MerchantUserUploadResVo;
import com.marvels.financial.pay.hlbpay.dto.response.OrderQueryResVo;
import com.marvels.financial.pay.hlbpay.dto.response.OrderResVo;
import com.marvels.financial.pay.hlbpay.dto.response.QueryOrderResponseVo;
import com.marvels.financial.pay.hlbpay.dto.response.QuickPayBindPayPreOrderResponseVo;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 合利宝底层接口
 * @author wujunfeng
 *
 */
public class HlbPayUtil {
	public static void main(String[] args) {
		// 身份证
		String idNo = "362527199503170530";
		// 姓名
		String name = "吴俊峰";
		// 电话号码
		String mobileNo = "15002089961";
		// 银行卡号
		String bankCard = "6228480128290266179";
		// 银行卡名称
		String banKCardName = "中国农业银行";
		try {
			// 1.预绑卡
			/*String preOrderNum = IdUtil.simpleUUID();
			HlbPrebindCardDTO preBindCardDTO = new HlbPrebindCardDTO();
			preBindCardDTO.setBankCardNo(bankCard);
			preBindCardDTO.setIdCard(idNo);
			preBindCardDTO.setMobile(mobileNo);
			preBindCardDTO.setName(name);
			preBindCardDTO.setOrderNum(preOrderNum);
			preBindCardDTO.setUserId(idNo);
			System.out.println("预绑卡订单号：" + preOrderNum);
			Map<String, Object> preData = HlbPayUtil.prebindCard(preBindCardDTO);
			System.out.println(JSONObject.toJSONString(preData));*/
			
			// 2.确认绑卡
			/*HlbBindCardDTO bindCardDTO = new HlbBindCardDTO();
			bindCardDTO.setOrderNum("07958c9b7a724e00b870a3740aca10ea");
			bindCardDTO.setSmsCode("469063");
			Map<String, Object> bindData = HlbPayUtil.bindCard(bindCardDTO);
			System.out.println(JSONObject.toJSONString(bindData));*/
			
			// 3.协议代扣
			/*String payOrderNum = IdUtil.simpleUUID();
			HlbDirectPaymentDTO directPaymentDTO = new HlbDirectPaymentDTO();
			directPaymentDTO.setAmount("0.11");
			directPaymentDTO.setBindId("158c6f63f1144fe5b73b1319503cc12e");
			directPaymentDTO.setLoanId("testloanid-----");
			directPaymentDTO.setMobile(mobileNo);
			directPaymentDTO.setOrderNum(payOrderNum);
			directPaymentDTO.setUserId(idNo);
			directPaymentDTO.setAppName("人人金贷");
			System.out.println("协议代扣订单号：" + payOrderNum);
			Map<String, Object> payData = HlbPayUtil.directPayment(directPaymentDTO);
			System.out.println(JSONObject.toJSONString(payData));*/
					
			// 4.代扣结果查询
			/*HlbDirectPaymentQueryDTO directPaymentQueryDTO = new HlbDirectPaymentQueryDTO();
			directPaymentQueryDTO.setOrderNum("9b56bd55a2a048b78a30a8a24c6ba7c4");
			Map<String, Object> resultData = HlbPayUtil.directPaymentQuery(directPaymentQueryDTO);
			System.out.println(JSONObject.toJSONString(resultData));*/
			
			// 5.用户注册
			/*String register = IdUtil.simpleUUID();
			McfeRepaymentTradeDetails registerDetail = new McfeRepaymentTradeDetails();
			registerDetail.setBankNumber(bankCard);
			registerDetail.setBankName(banKCardName);
			registerDetail.setIdNumber(idNo);
			registerDetail.setMobileNo(mobileNo);
			registerDetail.setCustName(name);
			registerDetail.setPayOrderNumber(register);
			System.out.println("用户注册订单号：" + register);
			HlbReturnDTO registerResult = HlbPayUtil.userRegister(registerDetail);
			System.out.println(JSONObject.toJSONString(registerResult));*/
			
			
			// 6.用户注册结果查询
			/*McfeRepaymentTradeDetails queryDetail = new McfeRepaymentTradeDetails();
			//queryDetail.setIdNumber(idNo);
			queryDetail.setPayOrderNumber("fbe56ab0b6e646a5baa3b6b618e11078");
			queryDetail.setHlbUserId("U1711486510");
			HlbReturnDTO queryResult = HlbPayUtil.userQuery(queryDetail);
			System.out.println(JSONObject.toJSONString(queryResult));*/
			
			//com.marvels.approve.credit.service.CreditReportService creditReportService1.getAttachmentsByViewKey
			
			// 7.资质上传
			// 身份证正面/身份证反面
			/*boolean result = true;
			for (int i = 0; i < 2; i++) {
				String orderId = IdUtil.simpleUUID();
				System.out.println(i + "----资质上传订单号：" + orderId);
				MerchantUserUploadVo userVo = new MerchantUserUploadVo();
				userVo.setP1_bizType("UploadCredential");
				userVo.setP3_orderId(orderId);
				userVo.setP4_userId("U1711486510");
				userVo.setP6_credentialType(i == 0 ? "FRONT_OF_ID_CARD" : "BACK_OF_ID_CARD");
				HlbReturnDTO queryResult = HlbPayUtil.userUpload(userVo, (i == 0 ? "D://6f41433cacb914ec486ca21816f8f63.jpg" : "D://eabf05c87cff5377564dbce4f433f78.jpg"));
				if(StrUtil.equals(queryResult.getCode(), "-1")){
					result = false;
				}
			}
			System.out.println("资质上传情况：" + result);*/
			
			
			// 7.代付
			String payOrderNumber = IdUtil.simpleUUID();
			McfeRepaymentTradeDetails tradeDetail = new McfeRepaymentTradeDetails();
			tradeDetail.setBankNumber(bankCard);
			tradeDetail.setBankName(banKCardName);
			tradeDetail.setIdNumber(idNo);
			tradeDetail.setMobileNo(mobileNo);
			tradeDetail.setCustName(name);
			tradeDetail.setHlbUserId("U1711486510");
			tradeDetail.setAmount("1");
			tradeDetail.setPayOrderNumber(payOrderNumber);
			System.out.println("代付订单号：" + payOrderNumber);
			Map<String, Object> payResult = HlbPayUtil.pay(tradeDetail);
			System.out.println("代付结果：" + JSONObject.toJSONString(payResult));
			
			// 8.代付结果查询
			/*McfeRepaymentTradeDetails tradeQueryDetail = new McfeRepaymentTradeDetails();
			tradeQueryDetail.setPayOrderNumber("28df89b105d947f898a30b42552b92a6");
			tradeQueryDetail.setHlbUserId("U1711486510");
			Map<String, Object> tradeQueryResult = HlbPayUtil.payResultQuery(tradeQueryDetail);
			System.out.println("代付结果：" + JSONObject.toJSONString(tradeQueryResult));*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 组合 鉴权下发短信
	 */
	public static Map<String, Object> prebindCard(HlbPrebindCardDTO bindCardDTO) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>预绑卡请求参数:" + bindCardDTO);
		if(StringUtils.isEmpty(bindCardDTO.getBankCardNo())){
			throw new MarvelsBusinessException("银行卡号不能为空");
		}
		if(StringUtils.isEmpty(bindCardDTO.getName())){
			throw new MarvelsBusinessException("持卡人姓名不能为空");
		}
		if(StringUtils.isEmpty(bindCardDTO.getMobile())){
			throw new MarvelsBusinessException("手机号不能为空");
		}
		if(StringUtils.isEmpty(bindCardDTO.getIdCard())){
			throw new MarvelsBusinessException("身份证不能为空");
		}
		if(StringUtils.isEmpty(bindCardDTO.getOrderNum())){
			throw new MarvelsBusinessException("订单号不能为空");
		}
		
		Map<String, Object> result=new HashMap<String, Object>();
		// 1.先进行鉴权绑卡预下单
		QuickPayBindCardPreOrderVo preBindCardDTO = new QuickPayBindCardPreOrderVo();
		preBindCardDTO.setP3_userId(bindCardDTO.getUserId());
		preBindCardDTO.setP4_orderId(bindCardDTO.getOrderNum());
		preBindCardDTO.setP6_payerName(bindCardDTO.getName());
		preBindCardDTO.setP8_idCardNo(bindCardDTO.getIdCard());
		preBindCardDTO.setP9_cardNo(bindCardDTO.getBankCardNo());
		preBindCardDTO.setP13_phone(bindCardDTO.getMobile());
		HlbReturnDTO preResult = HlbPayUtil.quickPayBindCardPreOrder(preBindCardDTO);
		if(!StrUtil.equals(preResult.getCode(), "0")){
			result.put("errormsg", preResult.getMsg());
			result.put("status","BIND_FAIL");
			result.put("errorcode", preResult.getThirdCode());
			return result;
		}
		// 2.预绑卡短信
		BindCardSendValidateCodeVo smsBindCardDTO = new BindCardSendValidateCodeVo();
		smsBindCardDTO.setP3_orderId(bindCardDTO.getOrderNum());
		HlbReturnDTO smsResult = HlbPayUtil.bindCardSendValidateCode(smsBindCardDTO);
		if(!StrUtil.equals(smsResult.getCode(), "0")){
			result.put("errormsg", smsResult.getMsg());
			result.put("status","BIND_FAIL");
			result.put("errorcode", smsResult.getThirdCode());
			return result;
		}
		
		result.put("errormsg","成功");
		result.put("status","TO_VALIDATE");//沿用易宝的预绑卡订单状态  TO_VALIDATE  待短验
		result.put("errorcode", smsResult.getThirdCode());
		return result;
	}

	/**
	 * 鉴权绑卡预下单
	 */
	
	public static HlbReturnDTO quickPayBindCardPreOrder(QuickPayBindCardPreOrderVo bindCardDTO){
		try {
			MarvelsLogUtil.getInstance().info("合利宝绑卡预下请求参数：" + JSONObject.toJSONString(bindCardDTO));
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			// 获取签名参数
			bindCardDTO.setP2_customerNumber(hlbConfig.getMerchantNo());
			Map<String, String> param = Sign.getReqestMap(bindCardDTO);
			
			// 请求
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));
			
			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				return HlbReturnDTO.fail("请求失败", null);
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				return HlbReturnDTO.fail(resultMsg, null);
			}

			BindCardPreOrderResponseVo responseVo = JSONObject.parseObject(resultMsg, BindCardPreOrderResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				return HlbReturnDTO.fail("验签失败", null);
			}

			if (!"0000".equals(responseVo.getRt2_retCode())) {
				return HlbReturnDTO.fail(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), null);
			}

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("P3_orderId", responseVo.getRt6_orderId());
			return HlbReturnDTO.success(responseVo.getRt2_retCode(), data);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("系统异常", e);
			return HlbReturnDTO.fail("合利宝鉴权绑卡预下单 - 系统异常", null);
		}
	}

	/**
	 * 鉴权绑卡短信
	 */
	public static HlbReturnDTO bindCardSendValidateCode(BindCardSendValidateCodeVo bindCardDTO){
		try {
			MarvelsLogUtil.getInstance().info("合利宝鉴权绑卡短信请求参数：" + JSONObject.toJSONString(bindCardDTO));
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			// 获取签名参数
			bindCardDTO.setP2_customerNumber(hlbConfig.getMerchantNo());
			Map<String, String> param = Sign.getReqestMap(bindCardDTO);
			// 请求
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));

			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				return HlbReturnDTO.fail("请求失败", null);
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				return HlbReturnDTO.fail(resultMsg, null);
			}

			BindCardSendValidateCodeResponseVo responseVo = JSONObject.parseObject(resultMsg, BindCardSendValidateCodeResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				return HlbReturnDTO.fail("验签失败", null);
			}

			if (!"0000".equals(responseVo.getRt2_retCode())) {
				return HlbReturnDTO.fail(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), null);
			}
			
			return HlbReturnDTO.success(responseVo.getRt2_retCode(), null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("系统异常", e);
			return HlbReturnDTO.fail("合利宝鉴权绑卡短信 - 系统异常", null);
		}
	}

	/**
	 * 确认鉴权绑卡
	 */
	public static Map<String, Object> bindCard(HlbBindCardDTO bindCardDTO) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>确定绑卡请求参数:" + JSON.toJSONString(bindCardDTO));
		//1 获取所需参数
		if(StringUtils.isEmpty(bindCardDTO.getSmsCode())){
			throw new MarvelsBusinessException("验证码不能为空");
		}
		if(StringUtils.isEmpty(bindCardDTO.getOrderNum())){
			throw new MarvelsBusinessException("订单号不能为空");
		}
		Map<String, Object> result=new HashMap<String, Object>();
		try {
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			// 获取签名参数
			ConfirmBindCardVo confirmBindCardVo = new ConfirmBindCardVo();
			confirmBindCardVo.setP2_customerNumber(hlbConfig.getMerchantNo());
			confirmBindCardVo.setP3_orderId(bindCardDTO.getOrderNum());
			confirmBindCardVo.setP5_validateCode(bindCardDTO.getSmsCode());
			Map<String, String> param = Sign.getReqestMap(confirmBindCardVo);
					
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));

			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				result.put("errormsg", "请求失败");
				result.put("status","BIND_FAIL");
				return result;
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				result.put("errormsg", resultMsg);
				result.put("status","BIND_FAIL");
				return result;
			}

			ConfirmBindCardResponseVo responseVo = JSONObject.parseObject(resultMsg, ConfirmBindCardResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				result.put("errormsg", "验签失败");
				result.put("status", "BIND_FAIL");
				return result;
			}

			if (StrUtil.equals(responseVo.getRt2_retCode(), "0000") && 
					StrUtil.equalsIgnoreCase(responseVo.getRt7_bindStatus(), "success")) {
				result.put("payToken", responseVo.getRt10_bindId());
				result.put("errormsg","成功");
				result.put("status","BIND_SUCCESS");
			}else{
				result.put("errormsg", responseVo.getRt3_retMsg());
				result.put("status", "BIND_FAIL");
			}
			result.put("errorcode", responseVo.getRt2_retCode());
			return result;
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("合利宝确认鉴权绑卡 - 系统异常", e);
			result.put("errormsg", "系统异常");
			result.put("status", "BIND_FAIL");
			return result;
		}
	}
	
	/**
	 * 协议代扣
	 */
	public static Map<String, Object> directPayment(HlbDirectPaymentDTO directPaymentDTO) throws MarvelsBusinessException {
		Map<String, Object> result=new HashMap<String, Object>();
		// 1.先预下单
		QuickPayBindPayPreOrderVo quickPayBindPayPreOrderVo = new QuickPayBindPayPreOrderVo();
		quickPayBindPayPreOrderVo.setP3_bindId(directPaymentDTO.getBindId());
		quickPayBindPayPreOrderVo.setP4_userId(directPaymentDTO.getUserId());
		quickPayBindPayPreOrderVo.setP5_orderId(directPaymentDTO.getOrderNum());
		quickPayBindPayPreOrderVo.setP8_orderAmount(directPaymentDTO.getAmount());
		quickPayBindPayPreOrderVo.setUserAccount(directPaymentDTO.getMobile());
		quickPayBindPayPreOrderVo.setAppName(directPaymentDTO.getAppName());
		HlbReturnDTO preOrderDto = HlbPayUtil.createOrder(quickPayBindPayPreOrderVo);
		if(!StrUtil.equals(preOrderDto.getCode(), "0")){
			// 预下单失败
			result.put("status", MarvelsConstant.FAILED);
			result.put("errormsg", preOrderDto.getMsg());
			return result;
		}
		
		// 2.确认下单
		ConfirmBindPayVo confirmBindPayVo = new ConfirmBindPayVo();
		confirmBindPayVo.setP3_orderId(directPaymentDTO.getOrderNum());
		HlbReturnDTO payDto = HlbPayUtil.confirmPay(confirmBindPayVo);
		
		// 转换成需要的参数
		result.put("status", payDto.getCode());
		result.put("errormsg", payDto.getMsg());
		result.put("errorcode", payDto.getThirdCode());
		Map<String, Object> payData = (Map<String, Object>) payDto.getData();
		result.put("r5_TrxNo", payData == null ? null : payData.get("thirdOrderNum"));//支付平台流水号
		return result;
	}

	
	/**
	 * 绑卡支付预下单
	 */
	
	public static HlbReturnDTO createOrder(QuickPayBindPayPreOrderVo quickPayBindPayPreOrderVo) throws MarvelsBusinessException {
		try {
			MarvelsLogUtil.getInstance().info("合利宝绑卡支付预下单参数：" + JSONObject.toJSONString(quickPayBindPayPreOrderVo));
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			// 组装参数并且获取签名参数
			quickPayBindPayPreOrderVo.setP2_customerNumber(hlbConfig.getMerchantNo());
			// 以下支付方有可能过审，所以必须要传
			quickPayBindPayPreOrderVo.setP9_goodsName("协议代扣");
			quickPayBindPayPreOrderVo.setP11_terminalType("MAC");
			quickPayBindPayPreOrderVo.setP12_terminalId(SystemTool.getMac());
			quickPayBindPayPreOrderVo.setP13_orderIp(SystemTool.getIPAddress());
			quickPayBindPayPreOrderVo.setGoodsQuantity("1");
			
			quickPayBindPayPreOrderVo.setAppType("H5");
			quickPayBindPayPreOrderVo.setAppName(quickPayBindPayPreOrderVo.getAppName().replace("金贷", "").replace("钱包", "").replace("贷", ""));
			quickPayBindPayPreOrderVo.setDealSceneType("O2O");
			Map<String, String> param = Sign.getReqestMap(quickPayBindPayPreOrderVo);
			
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));

			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				return HlbReturnDTO.fail("请求未发送成功", null);
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				return HlbReturnDTO.fail("支付方返回参数不合法", null);
			}

			QuickPayBindPayPreOrderResponseVo responseVo = JSONObject.parseObject(resultMsg, QuickPayBindPayPreOrderResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				return HlbReturnDTO.fail("验签失败", null);
			}
			
			if (!"0000".equals(responseVo.getRt2_retCode())) {
				return HlbReturnDTO.fail(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), null);
			}
			
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("P2_customerNumber", responseVo.getRt4_customerNumber());
			data.put("P3_orderId", responseVo.getRt5_orderId());
			return HlbReturnDTO.success(responseVo.getRt2_retCode(), data);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("合利宝绑卡支付预下单 - 系统异常", e);
			return HlbReturnDTO.fail("系统异常", null);
		}
	}
	
	/**
	 * 绑卡支付
	 */
	public static HlbReturnDTO confirmPay(ConfirmBindPayVo confirmBindPayVo) throws MarvelsBusinessException {
		try {
			MarvelsLogUtil.getInstance().info("合利宝绑卡支付参数：" + JSONObject.toJSONString(confirmBindPayVo));
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			// 组装参数并且获取签名参数
			confirmBindPayVo.setP2_customerNumber(hlbConfig.getMerchantNo());
			Map<String, String> param = Sign.getReqestMap(confirmBindPayVo);
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));
			
			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				return HlbReturnDTO.processing("非明确结果，需要重查状态", null);
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				return HlbReturnDTO.processing("支付方返回参数不合法", null);
			}
			
			ConfirmBindPayResponseVo responseVo = JSONObject.parseObject(resultMsg, ConfirmBindPayResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				return HlbReturnDTO.processing("验签失败", null);
			}
			
			Map<String, String> data = new HashMap<String, String>();
			data.put("thirdOrderNum", responseVo.getRt6_serialNumber());//合利宝交易流水号
			if(StrUtil.equals(responseVo.getRt2_retCode(), "0000")){
				if(StrUtil.equals(responseVo.getRt9_orderStatus(), "SUCCESS")){
					// 成功
					return HlbReturnDTO.success(responseVo.getRt2_retCode(), data);
				}else if(StrUtil.equals(responseVo.getRt9_orderStatus(), "DOING")){
					// 处理中
					return HlbReturnDTO.processing(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), data);
				}else{
					// 失败
					return HlbReturnDTO.fail(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), data);
				}
				
			}else if(StrUtil.equals(responseVo.getRt2_retCode(), "0001")){
				// 处理中
				return HlbReturnDTO.processing(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), data);
			}else{
				// 失败
				return HlbReturnDTO.fail(responseVo.getRt3_retMsg(), responseVo.getRt2_retCode(), data);
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("合利宝绑卡支付 - 系统异常", e);
			return HlbReturnDTO.fail("系统异常", null);
		}
	}
	
	/**
	 * 代扣结果查询
	 * @param directPaymentQueryDTO
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public static Map<String, Object> directPaymentQuery(HlbDirectPaymentQueryDTO directPaymentQueryDTO)
			throws MarvelsBusinessException {
		Map<String, Object> result=new HashMap<String, Object>();
		try {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>合利宝协议代扣结果查询请求参数:" + JSON.toJSONString(directPaymentQueryDTO));
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DK);
			// 设置签名需要的配置项
			Sign.setHlbConfig(hlbConfig);
			QueryOrderVo requestVo = new QueryOrderVo();
			requestVo.setP2_orderId(directPaymentQueryDTO.getOrderNum());
			requestVo.setP3_customerNumber(hlbConfig.getMerchantNo());
			Map<String, String> param = Sign.getReqestMap(requestVo);
			MarvelsLogUtil.getInstance().info("请求参数：" + JSONObject.toJSONString(param));
			Map<String, Object> resultMap = HttpClientService.getHttpResp(param, hlbConfig.getRequestUrl());
			MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));
			if ((Integer) resultMap.get("statusCode") != HttpStatus.SC_OK) {
				result.put("status", MarvelsConstant.PROCESSING);
				result.put("errormsg", "请求未发送成功");
				return result;
			}

			String resultMsg = (String) resultMap.get("response");
			if (!isJSON(resultMsg)) {
				result.put("status", MarvelsConstant.PROCESSING);
				result.put("errormsg", "支付方返回参数不合法");
				return result;
			}
			
			QueryOrderResponseVo responseVo = JSONObject.parseObject(resultMsg, QueryOrderResponseVo.class);
			if (!Sign.checkSign(responseVo)) {
				result.put("status", MarvelsConstant.PROCESSING);
				result.put("errormsg", "验签失败");
				return result;
			}
			
			if(StrUtil.equalsAny(responseVo.getRt2_retCode(), "0000", "8000")){
				if(StrUtil.equals(responseVo.getRt9_orderStatus(), "SUCCESS")){
					// 成功
					result.put("status", MarvelsConstant.SUCCESS);
					result.put("errormsg", "交易成功");
				}else if(StrUtil.equals(responseVo.getRt9_orderStatus(), "DOING")){
					// 处理中
					result.put("status", MarvelsConstant.PROCESSING);
					result.put("errormsg", responseVo.getRetReason());
				}else{
					// 失败
					result.put("status", MarvelsConstant.FAILED);
					result.put("errormsg", responseVo.getRetReason());
				}
			}else if(StrUtil.equals(responseVo.getRt2_retCode(), "0001")){
				// 处理中
				result.put("status", MarvelsConstant.PROCESSING);
				result.put("errormsg", responseVo.getRt3_retMsg());
			}else{
				// 失败
				result.put("status", MarvelsConstant.FAILED);
				result.put("errormsg", responseVo.getRt3_retMsg());
			}
			result.put("r5_TrxNo", responseVo.getRt10_serialNumber());//支付平台流水号
			result.put("errorcode", responseVo.getRt2_retCode());
			return result;
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("合利宝代扣订单查询 - 系统异常", e);
			result.put("status", MarvelsConstant.PROCESSING);
			result.put("errormsg", "系统异常");
			return result;
		}
	}
	
	
	/**
	 * 用户注册
	 * @param tradeDetail
	 * @return
	 */
	public static HlbReturnDTO userRegister(McfeRepaymentTradeDetails tradeDetail){
		// 加载配置项
		HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
		MerchantUserVo userVo = new MerchantUserVo();
		//信息域加密
        if (StringUtils.isNotBlank(tradeDetail.getIdNumber())) {
            userVo.setP5_legalPersonID(Des3Encryption.encode(hlbConfig.getDeskeyKey(), tradeDetail.getIdNumber()));
        }
        if (StringUtils.isNotBlank(tradeDetail.getMobileNo())) {
            userVo.setP6_mobile(Des3Encryption.encode(hlbConfig.getDeskeyKey(), tradeDetail.getMobileNo()));
        }
        userVo.setP2_customerNumber(hlbConfig.getMerchantNo());
        userVo.setP3_orderId(tradeDetail.getPayOrderNumber());
        userVo.setP4_legalPerson(tradeDetail.getCustName());
        // 拓展参数
        JSONObject ext = new JSONObject();
        ext.put("P3_orderId", tradeDetail.getPayOrderNumber());
        userVo.setP9_ext(ext.toString());
        try {
            Map<String, String> map = MyBeanUtils.convertBean(userVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));;
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("用户注册发送参数：" + JSONObject.toJSONString(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, hlbConfig.getRequestUrl(), null);
            MarvelsLogUtil.getInstance().info("用户注册响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                MerchantUserResVo merchantUserResVo = JSONObject.parseObject(resultMsg, MerchantUserResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(merchantUserResVo, null);
                MarvelsLogUtil.getInstance().info("用户注册组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = merchantUserResVo.getSign();
                MarvelsLogUtil.getInstance().info("用户注册响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(merchantUserResVo.getRt2_retCode())) {
                		JSONObject data = new JSONObject();
                		data.put("userId", merchantUserResVo.getRt6_userId());
                		data.put("userStatus", merchantUserResVo.getRt7_userStatus());
                		if(StrUtil.equals(merchantUserResVo.getRt7_userStatus(), "AVAILABLE")){
            				//注册成功
                			return HlbReturnDTO.success(merchantUserResVo.getRt2_retCode(), data);
                		}else if(StrUtil.equalsAny(merchantUserResVo.getRt7_userStatus(), "INIT", "AUDITING")){
                			// 处理中
                			return HlbReturnDTO.processing(merchantUserResVo.getRt3_retMsg(), data);
                		}else{
                			// 失败
	       					return HlbReturnDTO.fail(merchantUserResVo.getRt3_retMsg(), merchantUserResVo.getRt2_retCode(), data);
                		}
                    } else {
                    	// 失败
    					return HlbReturnDTO.fail(merchantUserResVo.getRt3_retMsg(), merchantUserResVo.getRt2_retCode(), null);
                    }
                } else {
                	// 失败
					return HlbReturnDTO.fail("验签失败", null);
                }
            } else {
            	// 失败
				return HlbReturnDTO.fail("请求失败", null);
            }
        } catch (Exception e) {
        	MarvelsLogUtil.getInstance().error("用户注册发生异常：", e);
            return HlbReturnDTO.fail("交易异常", null);
        }
	}
	
	/**
	 * 用户资质上传
	 * @param userVo
	 * @param imgPath
	 * @return
	 */
	public static HlbReturnDTO userUpload(MerchantUserUploadVo userVo, String imgPath){
		try {
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
			userVo.setP2_customerNumber(hlbConfig.getMerchantNo());
            File file = new File(imgPath);
            // 文件签名
            try (InputStream is = new FileInputStream(file)){
                userVo.setP7_fileSign(DigestUtils.md5DigestAsHex(is));
            }
            Map<String, String> map = MyBeanUtils.convertBean(userVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("用户资质上传发送参数：" + JSONObject.toJSONString(map));
            Map resultMap = HttpClientService.getHttpResp(map, hlbConfig.getFileUploadUrl(), file);
            MarvelsLogUtil.getInstance().info("用户资质上传响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                MerchantUserUploadResVo resVo = JSONObject.parseObject(resultMsg, MerchantUserUploadResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(resVo, null);
                MarvelsLogUtil.getInstance().info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resVo.getSign();
                MarvelsLogUtil.getInstance().info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                    if(StrUtil.equals(resVo.getRt2_retCode(), "0000") && StrUtil.equals(resVo.getRt7_credentialStatus(), "UPLOADED")){
                    	return HlbReturnDTO.success(resVo.getRt2_retCode(), null);
                    }else{
                    	return HlbReturnDTO.fail(resVo.getRt8_desc(), resVo.getRt2_retCode(), null);
                    }
                } else {
                	// 失败
					return HlbReturnDTO.fail("验签失败", null);
                }
            } else {
            	// 失败
				return HlbReturnDTO.fail("请求失败", null);
            }
        } catch (Exception e) {
        	MarvelsLogUtil.getInstance().error("用户注册发生异常：", e);
            return HlbReturnDTO.fail("交易异常", null);
        }
	}
	
	/**
	 * 用户资质查询
	 * @return
	 */
	public static HlbReturnDTO userUploadQuery(MerchantUserUploadVo userVo){
		try {
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
			userVo.setP2_customerNumber(hlbConfig.getMerchantNo());
            String[] excludes = {"P7_fileSign"};
            Map<String, String> map = MyBeanUtils.convertBean(userVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));;
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("用户资质查询发送参数：" + JSONObject.toJSONString(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, hlbConfig.getRequestUrl(), null);
            MarvelsLogUtil.getInstance().info("用户资质查询响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                MerchantUserUploadResVo resVo = JSONObject.parseObject(resultMsg, MerchantUserUploadResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(resVo, null);
                MarvelsLogUtil.getInstance().info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resVo.getSign();
                MarvelsLogUtil.getInstance().info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                	if(StrUtil.equals(resVo.getRt2_retCode(), "0000") && StrUtil.equals(resVo.getRt7_credentialStatus(), "UPLOADED")){
                    	return HlbReturnDTO.success(resVo.getRt2_retCode(), null);
                    }else{
                    	return HlbReturnDTO.fail(resVo.getRt8_desc(), resVo.getRt2_retCode(), null);
                    }
                } else {
                	// 失败
					return HlbReturnDTO.fail("验签失败", null);
                }
            } else {
            	// 失败
				return HlbReturnDTO.fail("请求失败", null);
            }
        } catch (Exception e) {
        	MarvelsLogUtil.getInstance().error("用户注册发生异常：", e);
            return HlbReturnDTO.fail("交易异常", null);
        }
	}
	
	/**
	 * 用户查询
	 * @param tradeDetail
	 * @return
	 */
	public static HlbReturnDTO userQuery(McfeRepaymentTradeDetails tradeDetail){
		// 加载配置项
		HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
		MerchantUserQueryVo userVo = new MerchantUserQueryVo();
		userVo.setP2_customerNumber(hlbConfig.getMerchantNo());
		userVo.setP3_orderId(tradeDetail.getPayOrderNumber());
		userVo.setP4_userId(tradeDetail.getHlbUserId());
		try {
            Map<String, String> map = MyBeanUtils.convertBean(userVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));;
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("用户注册结果查询发送参数：" + JSONObject.toJSONString(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, hlbConfig.getRequestUrl(), null);
            MarvelsLogUtil.getInstance().info("用户注册结果查询响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                MerchantUserQueryResVo resVo = JSONObject.parseObject(resultMsg, MerchantUserQueryResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(resVo, null);
                MarvelsLogUtil.getInstance().info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resVo.getSign();
                MarvelsLogUtil.getInstance().info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                	if ("0000".equals(resVo.getRt2_retCode())) {
                		JSONObject data = new JSONObject();
                		data.put("userId", resVo.getRt6_userId());
                		data.put("userStatus", resVo.getRt7_userStatus());
                		if(StrUtil.equals(resVo.getRt7_userStatus(), "AVAILABLE")){
            				//注册成功
                			return HlbReturnDTO.success(resVo.getRt2_retCode(), data);
                		}else if(StrUtil.equalsAny(resVo.getRt7_userStatus(), "INIT", "AUDITING")){
                			// 处理中
                			return HlbReturnDTO.processing(resVo.getRt8_desc(), data);
                		}else{
                			// 失败
	       					return HlbReturnDTO.fail(resVo.getRt8_desc(), resVo.getRt2_retCode(), data);
                		}
                    } else {
                    	// 失败
    					return HlbReturnDTO.fail(resVo.getRt3_retMsg(), resVo.getRt2_retCode(), null);
                    }
                } else {
                	// 失败
					return HlbReturnDTO.processing("验签失败", null);
                }
            } else {
            	return HlbReturnDTO.processing("请求失败", null);
            }
        } catch (Exception e) {
        	MarvelsLogUtil.getInstance().error("查询用户注册结果发生异常：", e);
            return HlbReturnDTO.processing("交易异常", null);
        }
	}
	
	
	/**
	 * 代付
	 * @param tradeDetail
	 * @return
	 */
	public static Map<String, Object> pay(McfeRepaymentTradeDetails tradeDetail) {
		Map<String, Object> result = new HashMap<String, Object>();
		// 加载配置项
		HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
		OrderVo orderVo = new OrderVo();
		if (StringUtils.isNotBlank(tradeDetail.getBankNumber())) {
            orderVo.setP10_bankAccountNo(Des3Encryption.encode(hlbConfig.getDeskeyKey(), tradeDetail.getBankNumber()));
        }
        if (StringUtils.isNotBlank(tradeDetail.getIdNumber())) {
            orderVo.setP11_legalPersonID(Des3Encryption.encode(hlbConfig.getDeskeyKey(), tradeDetail.getIdNumber()));
        }
        if (StringUtils.isNotBlank(tradeDetail.getMobileNo())) {
            orderVo.setP12_mobile(Des3Encryption.encode(hlbConfig.getDeskeyKey(), tradeDetail.getMobileNo()));
        }
        
        orderVo.setP2_customerNumber(hlbConfig.getMerchantNo());
        orderVo.setP3_orderId(tradeDetail.getPayOrderNumber());
        orderVo.setP4_userId(tradeDetail.getHlbUserId());
        orderVo.setP7_amount(tradeDetail.getAmount());
        orderVo.setP9_bankAccountName(tradeDetail.getCustName());
        orderVo.setP17_bankCode(BankCodeEnum.getCode(tradeDetail.getBankName()));
        
        // 借款信息
        JSONObject loanConInfo = new JSONObject();
        loanConInfo.put("loanTime", "7");//借款时间
        loanConInfo.put("loanTimeUnit", "D");//借款时间单位:D-天;M-月;Y-年
        loanConInfo.put("loanInterestRate", "36.00");//年利率 格式0.00,如18%则填18.00
        loanConInfo.put("periodization", "7");//分期数
        loanConInfo.put("periodizationDays", "1");//每期天/月/年数  (正整数,单位以LoanTimeUnit为准)
        // 分期金额=（借款金额+借款金额×借款年利率÷360×借款天数）÷分期数，借款金额就是接口传的订单金额
        double periodizationFee = (Double.parseDouble(tradeDetail.getAmount()) + 
        		Double.parseDouble(tradeDetail.getAmount()) * loanConInfo.getDoubleValue("loanInterestRate") / 100 / 360 * 7) / 
        		loanConInfo.getDoubleValue("periodization");
        // 最小值为0.01
        loanConInfo.put("periodizationFee", NumberUtil.isLess(NumberUtil.roundDown(periodizationFee, 2), new BigDecimal("0.01")) ? "0.01" : NumberUtil.roundDown(periodizationFee, 2).toString());
        orderVo.setP21_loanConInfo(loanConInfo.toJSONString());
        try {
            Map<String, String> map = MyBeanUtils.convertBean(orderVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));;
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("代付发送参数：" + JSONObject.toJSONString(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, hlbConfig.getRequestUrl(), null);
            MarvelsLogUtil.getInstance().info("代付响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                OrderResVo resVo = JSONObject.parseObject(resultMsg, OrderResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(resVo, null);
                MarvelsLogUtil.getInstance().info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resVo.getSign();
                MarvelsLogUtil.getInstance().info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                    if(StrUtil.equals(resVo.getRt2_retCode(), "0000")){
                    	if(StrUtil.equals(resVo.getRt8_orderStatus(), "SUCCESS")){
                    		result.put("errorCode",MarvelsConstant.SUCCESS);
                    		result.put("errorMsg","代付交易成功");
                    	}else if(StrUtil.equals(resVo.getRt8_orderStatus(), "FAIL")){
                    		result.put("result", "-1");
                    		result.put("errorCode", MarvelsConstant.FAILED);
    	    				result.put("errorMsg", resVo.getRt3_retMsg());
                    	}else{
                    		result.put("result", "1");
                    		result.put("errorCode", MarvelsConstant.PROCESSING);
                    		result.put("errorMsg", resVo.getRt3_retMsg());
                    	}
                    }else{
                    	// 失败
                    	result.put("result", "-1");
                    	result.put("errorCode", MarvelsConstant.FAILED);
                    	result.put("errorMsg", resVo.getRt3_retMsg());
                    }
                } else {
                	result.put("result", "1");
                	result.put("errorCode", MarvelsConstant.PROCESSING);
                	result.put("errorMsg", "验签失败");
                }
            } else {
            	result.put("result", "1");
            	result.put("errorCode", MarvelsConstant.PROCESSING);
            	result.put("errorMsg", "请求失败");
            }
        } catch (Exception e) {
        	MarvelsLogUtil.getInstance().error("代付系统异常", e);
        	result.put("result", "1");
        	result.put("errorCode", MarvelsConstant.PROCESSING);
        	result.put("errorMsg", "交易异常");
        }
        return result;
	}
	
	/**
	 * 代付结果查询
	 * @param tradeDetail
	 * @return
	 */
	public static Map<String, Object> payResultQuery(McfeRepaymentTradeDetails tradeDetail) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 加载配置项
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
			// 设置参数
			OrderQueryVo orderVo = new OrderQueryVo();
			orderVo.setP2_customerNumber(hlbConfig.getMerchantNo());
			orderVo.setP4_userId(tradeDetail.getHlbUserId());
			orderVo.setP3_orderId(tradeDetail.getPayOrderNumber());
			// 签名
            Map<String, String> map = MyBeanUtils.convertBean(orderVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSigned(map, null);
            MarvelsLogUtil.getInstance().info("签名原文串：" + oriMessage);
            String sign = RSA.sign(oriMessage.trim(), RSA.getPrivateKey(hlbConfig.getSignKeyPrivate()));
            MarvelsLogUtil.getInstance().info("签名串：" + sign);
            map.put("sign", sign);
            MarvelsLogUtil.getInstance().info("发送参数：" + JSONObject.toJSONString(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, hlbConfig.getRequestUrl(), null);
            MarvelsLogUtil.getInstance().info("响应结果：" + JSONObject.toJSONString(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                OrderQueryResVo resVo = JSONObject.parseObject(resultMsg, OrderQueryResVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSigned(resVo, null);
                MarvelsLogUtil.getInstance().info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resVo.getSign();
                MarvelsLogUtil.getInstance().info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim() + Constant.split + hlbConfig.getSignkey());
                if (checkSign.equals(responseSign)) {
                    if(StrUtil.equals(resVo.getRt2_retCode(), "0000")){
                    	if(StrUtil.equals(resVo.getRt8_orderStatus(), "SUCCESS")){
                    		// 放款成功
                    		result.put("result", "0");
    	    				result.put("errorCode",MarvelsConstant.SUCCESS);
    	    				result.put("errorMsg","放款成功");
                    	}else if(StrUtil.equals(resVo.getRt8_orderStatus(), "FAIL")){
                    		// 放款失败
                    		result.put("result", "-1");
                    		result.put("errorCode", MarvelsConstant.SUCCESS);
                    		result.put("errorMsg", resVo.getRt9_desc());
                    	}else{
                    		result.put("result", "1");
                    		result.put("errorCode", MarvelsConstant.SUCCESS);
    	    				result.put("errorMsg", resVo.getRt9_desc());
                    	}
                    }else if(StrUtil.equalsAny(resVo.getRt2_retCode(), "1001", "1015","8104","8106")){
                    	// 需要重查结果
                    	result.put("result", "1");
	    				result.put("errorCode",MarvelsConstant.SUCCESS);
	    				result.put("errorMsg", resVo.getRt3_retMsg());
                    }else{
                    	// 失败
                    	result.put("result", "-1");
                    	result.put("errorCode", MarvelsConstant.SUCCESS);
                    	result.put("errorMsg", resVo.getRt3_retMsg());
                    }
                } else {
                	// 非法情况，需要重新查询
                	result.put("result", "1");
                	result.put("errorCode", MarvelsConstant.SUCCESS);
                	result.put("errorMsg", "验签失败");
                }
            } else {
            	// 非法情况，需要重新查询
            	result.put("result", "1");
            	result.put("errorCode", MarvelsConstant.FAILED);
            	result.put("errorMsg", "请求失败");
            }
        } catch (Exception e) {
        	// 非法情况，需要重新查询
        	MarvelsLogUtil.getInstance().error("代付结果查询系统异常", e);
        	result.put("result", "1");
        	result.put("errorCode", MarvelsConstant.FAILED);
        	result.put("errorMsg", "请求异常");
        }
        return result;
	}
	public static boolean isJSON(String test) {
		try {
			JSONObject.parseObject(test);
		} catch (JSONException ex) {
			return false;
		}
		return true;
	}

}
